from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.response import Response
from QQLoginTool.QQtool import OAuthQQ
from django.conf import settings
from rest_framework import status
import logging
from rest_framework_jwt.settings import api_settings

from .models import OAuthQQUser
from .utils import generate_save_user_token
from . import serializers

# Create your views here.

# 创建日志输出器
logger = logging.getLogger('django')

class OauthUserView(APIView):
    """实现oauth_2.0认证
    使用code获取accesstoken,在使用accesstoken获取openid
    """
    def get(self,request):
        # 提取code请求参数
        code = request.query_params.get('code')
        if not code:
            return Response({'message':'缺少code'},status=status.HTTP_400_BAD_REQUEST)

        # 创建SDK对象
        oauth = OAuthQQ(client_id=settings.QQ_CLIENT_ID, client_secret=settings.QQ_CLIENT_SECRET, redirect_uri=settings.QQ_REDIRECT_URI)

        try:
            # 使⽤code向QQ服务器请求access_token
            access_token = oauth.get_access_token(code)

            # 使⽤access_token向QQ服务器请求openid
            open_id = oauth.get_open_id(access_token)
        except Exception as e:
            logger.info(e)
            return Response({'message':'QQ服务器错误'},status=status.HTTP_503_SERVICE_UNAVAILABLE)

        # 使⽤openid查询该QQ⽤户是否在美多商城中绑定过⽤户
        try:
            oauthqquser_model = OAuthQQUser.objects.get(openid=open_id)
        except OAuthQQUser.DoesNotExist:
            # 如果openid没绑定美多商城⽤户，创建⽤户并绑定到openid
            # return '响应open_id'
            # return Response({'open_id':open_id})  # 不安全
            # 为了保证响应openid的安全性,需要先对openid签名,再响应
            token_openid = generate_save_user_token(open_id)
            return Response({'access_token':token_openid})
        else:
            # 如果openid已绑定美多商城⽤户，直接⽣成JWT token，并返回
            # 获取到绑定的user
            qq_user = oauthqquser_model.user

            # 生成JWT token
            jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
            jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER

            # 使用注册后的User信息,生成载荷
            payload = jwt_payload_handler(qq_user)
            # 使用载荷生成JWT token
            token = jwt_encode_handler(payload)

            return Response({
                'token': token,
                'username': qq_user.username,
                'user_id': qq_user.id,
            })

    def post(self,request):
        """使用openid绑定用户id"""
        # 创建序列化器对象
        serializer = serializers.QQAuthUserSerializer(data=request.data)

        # 开启校验
        serializer.is_valid(raise_exception=True)

        # 执行保存行为
        qq_user = serializer.save()

        # 绑定用户成功,需要生成JWT token,并返回
        # 生成JWT token
        jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
        jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER

        # 使用注册后的User信息,生成载荷
        payload = jwt_payload_handler(qq_user)
        # 使用载荷生成JWT token
        token = jwt_encode_handler(payload)

        return Response({
            'token': token,
            'username': qq_user.username,
            'user_id': qq_user.id,
        })


class OauthURLView(APIView):
    """返回QQ扫码登陆链接"""

    def get(self,request):

        # 获取next参数
        next = request.query_params.get('next')

        # 创建SDK对象
        oauth = OAuthQQ(client_id=settings.QQ_CLIENT_ID, client_secret=settings.QQ_CLIENT_SECRET, redirect_uri=settings.QQ_REDIRECT_URI, state=next)

        # 调用SDK的方法,得到QQ扫码登录链接
        login_url = oauth.get_qq_url()

        # 返回QQ扫码登录链接
        return Response({"login_url": login_url})